package com.goldman.aplt.service.packet;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goldman.aplt.base.constant.ApConstants;
import com.goldman.aplt.entity.packet.ApsOutLog;
import com.goldman.aplt.repo.packet.ApsOutLogMapper;
import com.goldman.aplt.service.parameter.AppSystemParameterService;
import com.goldman.aplt.util.CommUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class ApsOutLogService extends ServiceImpl<ApsOutLogMapper, ApsOutLog> {
    @Autowired
    private ApsPacketExtendService apsPacketExtendService;

    @Autowired
    private AppSystemParameterService appSystemParameterService;

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void regOutLog(String url, String callSeq, String begin, String req, String resp, long executeTime) {
        // 过滤不需要Log的接口
        if (appSystemParameterService.exists(ApConstants.FILTER_CALLOUT_LOG_KEY, url)) {
            log.info("api call out log filter, url={}", url);
            return;
        }

       try {
           ApsOutLog log = new ApsOutLog();
           log.setTrxnSeq(CommUtil.getTrxnEnvs().getTrxn_seq());
           log.setBusiSeq(CommUtil.getTrxnEnvs().getBusi_seq());
           log.setCallOutSeq(callSeq);
           log.setOutUrl(url);
           log.setBeginTime(begin);
           log.setEndTime(CommUtil.getComputerDateTime());
           log.setUsedTime((int) executeTime);
           if (req.length() > 4000 || resp.length() > 4000) {
               apsPacketExtendService.initApsPacketExtend(CommUtil.getTrxnEnvs().getTrxn_seq(), req, resp);
           } else {
               log.setRequest(req);
               log.setResponse(resp);
           }
           save(log);
       } catch (Exception e) {
           //日志登记失败不能影响交易
           log.error("登记外调流水日志失败{}", e.getMessage(), e);
       }
    }
}
